package com.dxt.controller;

import com.dxt.pojo.User;
import com.dxt.service.UserService;
import com.dxt.service.UserServiceImpl;
import com.dxt.utils.MD5Util;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.SneakyThrows;

import java.io.IOException;

/**
 * BelongProject: deliveryManage
 * BelongPackage: com.dxt.controller
 * Description:
 *
 * @Author 段鑫涛
 * @Create 2025/3/30 21:59
 * @Version 1.0
 */
@WebServlet("/login")
public class UserLoginController extends HttpServlet {
    private UserService userService = new UserServiceImpl();

    @Override
    @SneakyThrows
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        User user = userService.getUserByUsername(username);

        if (user != null) {
            if (MD5Util.encrypt(password).equals(user.getPassword())) {
                HttpSession session = req.getSession();
                session.setAttribute("user", user);
                resp.sendRedirect("/index.jsp");
            }else{
                req.getRequestDispatcher("/WEB-INF/loginPasswordError.html").forward(req, resp);
            }
        } else {
            req.getRequestDispatcher("/WEB-INF/loginUsernameError.html").forward(req, resp);
        }
    }
}
